package org.example.nio_demo;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @ClassName Demo5
 * @Description
 * @Author zhangsw
 * @Date 2020/11/11 22:35
 * @Version 1.0
 */
public class Demo5 {

    /**
     * 分散和聚集
     *
     * @param args
     */
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf1 = new RandomAccessFile("abc.txt", "rw");
        //获取通道
        FileChannel channel1 = raf1.getChannel();

        //指定缓冲区
        ByteBuffer buffer1 = ByteBuffer.allocate(100);
        ByteBuffer buffer2 = ByteBuffer.allocate(1024);

        //分散读取
        ByteBuffer[] bufs = {buffer1, buffer2};
        channel1.read(bufs);

        for (ByteBuffer buf : bufs) {
            buf.flip();
        }

        System.err.println(new String(bufs[0].array(), 0, bufs[0].limit()));
        System.out.println("---------------------------");
        System.err.println(new String(bufs[1].array(), 0, bufs[1].limit()));

        //聚集写入
        RandomAccessFile raf2 = new RandomAccessFile("abc2.txt", "rw");
        FileChannel channel2 = raf2.getChannel();
        channel2.write(bufs);
    }
}
